RESET:
	SEI          ; disable IRQs
	CLD          ; disable decimal mode
	LDX #$40
	STX $4017    ; disable APU frame IRQ
	LDX #$FF
	TXS          ; Set up stack
	INX          ; now X = 0
	STX $2000    ; disable NMI
	STX $2001    ; disable rendering
	STX $4010    ; disable DMC IRQs

	JSR SCORE_COPY_TO_HIGH

; clear variables
clrmem:
	LDA #$00
	STA $0000,x
	INX
	BNE clrmem

	LDA VAR_GAME_STATUS
	LDA VAR_RANDOM_SEED

	MACRO_WAIT_FOR_VBLANK

	; loading data
	JSR LOAD_PALETTES
	JSR LOAD_ATTRIBUTES
	JSR LOAD_BACKGROUNDS
	JSR LOAD_SPRITES

	LDA #INITIAL_OBSTACLE_SPACING
	STA VAR_OBSTACLE_SPACING

	LDA #GAME_RESET_WAIT
	STA VAR_RESET_WAIT

	LDA VAR_GAME_STATUS
	CMP #GAME_STATUS_INITIAL
	BNE FILL_HORIZON_LINE
	JMP FILL_HORIZON_LINE_END


FILL_HORIZON_LINE:
	LDA #$22
	STA PPU_ADDR
	LDX #$00
	LDA #TRANSITION_COLUMN_OFFSET
	STA PPU_ADDR
.Loop
	LDA BIN_HORIZON_LINE,x
	STA PPU_DATA
	INX
	CPX #$1D
	BNE .Loop

	MACRO_WAIT_FOR_VBLANK
	MACRO_DINO_ADD_X $1B

	LDA #GAME_STATUS_RUN
	STA VAR_GAME_STATUS
FILL_HORIZON_LINE_END:

	; ; reset ppu
	LDA #$00
	STA PPU_ADDR
	STA PPU_ADDR
	STA PPU_SCROLL
	STA PPU_SCROLL

	LDA #INIT_PPU_CTRL
	STA PPU_CTRL

	LDA #INIT_PPU_MASK
	STA PPU_MASK

	; set the bg high for drawing obstacle
	LDA #$26
	STA VAR_BG_HIGH

	MACRO_INFINITE_LOOP

NMI:
	; do actions for each frame
	; the drawing should finished in the vblank
	; all drawing code should be executed first
	LDA #<(MEM_LAYOUT_SPR)
	STA PPU_OAM_ADDR
	LDA #>(MEM_LAYOUT_SPR)
	STA PPU_OAM_DMA


	LDA VAR_GAME_STATUS
	CMP #GAME_STATUS_INITIAL
	BEQ LABEL_GAME_INITIAL
	CMP #GAME_STATUS_TRANSITION_1
	BEQ LABEL_GAME_TRANSITION_1
	CMP #GAME_STATUS_TRANSITION_2
	BEQ LABEL_GAME_TRANSITION_2
	CMP #GAME_STATUS_RUN
	BEQ LABEL_GAME_RUNNING
	CMP #GAME_STATUS_OVER
	BEQ LABEL_GAME_OVER

LABEL_GAME_INITIAL:
	JSR GAME_INITIAL
	JMP RENDER_END

LABEL_GAME_TRANSITION_1:
	JSR DRAW_DINO
	JSR GAME_TRANSITION_1
	JMP RENDER_END

LABEL_GAME_TRANSITION_2:
	JSR DRAW_DINO
	JSR GAME_TRANSITION_2
	JMP RENDER_END

LABEL_GAME_RUNNING:
	JSR DRAW_DINO
	JSR SCORE_ADD
	JSR GAME_RUNNING
	JMP RENDER_END

LABEL_GAME_OVER:
	LDA VAR_RESET_WAIT
	CMP #$00
	BEQ LABEL_GAME_OVER_RESET
	DEC VAR_RESET_WAIT
	JMP RENDER_END

LABEL_GAME_OVER_RESET:
	JSR GAME_OVER
	JMP RENDER_END

RENDER_END:
	LDA #$00
	STA PPU_SCROLL
	LDA #$00
	STA PPU_SCROLL
	LDA #INIT_PPU_CTRL
	STA PPU_CTRL

	MACRO_WAIT_FOR_SPRITE0

	LDA VAR_SCREEN_SCROLL_X
	STA PPU_SCROLL
	LDA #$00
	STA PPU_SCROLL
	LDA #INIT_PPU_CTRL
	ORA VAR_NAMETABLE_MASK
	STA PPU_CTRL

	; game logic
	JSR HANDLE_INPUT

END:
	RTI
